package encaps.utils;

import encaps.action.*;
import encaps.entities.*;
import encaps.resources.Grants;
import encaps.resources.Image;
import encaps.resources.Labels;
import encaps.resources.Response;
import encaps.security.RoleManager;
import encaps.security.SecuritySystem;
import java.io.*;
import java.sql.SQLException;
import java.text.DecimalFormat;
import java.util.*;
import javax.naming.NamingException;
import org.jdom.Element;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;

public class XMLHelper {

    public static final int VIEW = 1;
    public static final int EDIT = 2;
    public static final int DELETE = 4;

    private XMLHelper() {
    }

    /**
     * Returns formatted string representation of given XML element.
     *
     * @param element element to represent.
     * @return String containing XML element.
     */
    public static String toString(Element element) {
        if (element == null) {
            return "";
        }
        StringWriter writer = new StringWriter();
        XMLOutputter xmlOutputter = new XMLOutputter();
        xmlOutputter.setFormat(Format.getPrettyFormat());
        try {

            xmlOutputter.output(element, writer);
        } catch (IOException ex) {
        }
        return writer.toString();
    }

    public static Element toXMLElement(UserLocal user, String header, Role role, Boolean edit) {
        Element response = createElement(Response.RESPONSE);
        Element e = addChild(response, Response.ENTITY);
        if (edit != null) {
            e.setAttribute(Response.EDIT, edit.toString());
        } else {
            e.setAttribute(Response.EDIT, "false");
        }

        String info = user.getInfo();
        String email = user.getEmail();
        String contacts = user.getContacts();
        String image = user.getAvatar();
        String urole = user.getRole();

        addChild(e, createHeader(header));
        addChild(e, createImage(image, EditProfileAction.PICTURE));
        if (edit != null && edit) {
            addChild(e, createPasswordField(Labels.getLabel(Labels.OLD_PASSWORD), EditProfileAction.OLD_PASSWORD));
            addChild(e, createPasswordField(Labels.getLabel(Labels.NEW_PASSWORD), EditProfileAction.NEW_PASSWORD));
        }
        addChild(e, createTextArea(Labels.getLabel(Labels.INFO), info, EditProfileAction.INFO));
        addChild(e, createTextField(Labels.getLabel(Labels.EMAIL), email, EditProfileAction.EMAIL));
        addChild(e, createTextField(Labels.getLabel(Labels.CONTACTS), contacts, EditProfileAction.CONTACTS));
        addChild(e, createHiddenTextField(user.getID(), Action.ID));
        //если edit == null - user-а просматривает другой user
        if (edit == null) {
            addChild(e, createTextField(Labels.getLabel(Labels.ROLE), urole, EditUserAction.ROLE));
            if (role.hasGrant(Grants.EDIT_USER)) {

                addChild(e, createField(Image.getImage(Image.EDIT), EditUserAction.EDIT_USER, Action.ACTION, Response.IMAGEBUTTON));
            }
            if (role.hasGrant(Grants.DELETE_USER)) {
                addChild(e, createField(Image.getImage(Image.DELETE), DeleteUserAction.DELETE_USER, Action.ACTION, Response.IMAGEBUTTON));
            }
        } //если edit == true user редактирует свой профиль
        else if (edit) {
            if (role.hasGrant(Grants.EDIT_PROFILE)) {
                addChild(e, createField(Image.getImage(Image.APPLY), ApplyProfileChangesAction.APPLY_PROFILE_CHANGES, Action.ACTION, Response.IMAGEBUTTON));
            }
        } //если edit == false user просматривает свой профиль
        else {
            if (role.hasGrant(Grants.EDIT_PROFILE)) {
                addChild(e, createField(Image.getImage(Image.EDIT), EditProfileAction.EDIT_PROFILE, Action.ACTION, Response.IMAGEBUTTON));
            }
            if (role.hasGrant(Grants.DELETE_PROFILE)) {
                addChild(e, createField(Image.getImage(Image.DELETE), DeleteProfileAction.DELETE_PROFILE, Action.ACTION, Response.IMAGEBUTTON));
            }
        }

        return response;
    }

    public static Element toXMLElement(PersonLocal person, String header, Boolean edit, ActionContext context) {
        Element response = createElement(Response.RESPONSE);
        Element e = addChild(response, Response.ENTITY);
        e.setAttribute(Response.EDIT, edit.toString());

        String name = person.getName();
        String bio = person.getBio();
        String image = person.getPhoto();

        addChild(e, createHeader(header));
        addChild(e, createImage(image, ShowEmptyPersonPageAction.PERSON_PIC));

        addChild(e, createTextField(Labels.getLabel(Labels.PERSON_NAME), name, ShowEmptyPersonPageAction.PERSON_NAME));
        addChild(e, createTextArea(Labels.getLabel(Labels.PERSON_BIOGRAPHY), bio, ShowEmptyPersonPageAction.PERSON_BIOGRAPHY));
//        addChild(e, createTextField(Labels.getLabel(Labels.CONTACTS), contacts, EditProfileAction.CONTACTS));
        MoviePersonInfo mpi;
        if (edit) {
            addChild(e, createImageButton(Image.getImage(Image.APPLY), ApplyPersonChangesAction.APPLY_PERSON_CHANGES));
        } else {
            Set<MoviePersonInfo> movies = person.getMovies();
            addChild(e, createSmallHeader(Labels.getLabel(Labels.MOVIE_PERSON_ACTOR)));
            for (MoviePersonInfo info : movies) {
                if (info.getType().equals(MoviePersonInfo.ACTOR)) {
                    addChild(e, createLink(info.getName(), "viewMovie", info.getId()));
                }
            }
            addChild(e, createSmallHeader(Labels.getLabel(Labels.MOVIE_PERSON_DIRECTOR)));
            for (MoviePersonInfo info : movies) {
                if (info.getType().equals(MoviePersonInfo.DIRECTOR)) {
                    addChild(e, createLink(info.getName(), "viewMovie", info.getId()));
                }
            }
            addChild(e, createSmallHeader(Labels.getLabel(Labels.MOVIE_PERSON_PRODUCER)));
            for (MoviePersonInfo info : movies) {
                if (info.getType().equals(MoviePersonInfo.PRODUCER)) {
                    addChild(e, createLink(info.getName(), "viewMovie", info.getId()));
                }
            }

            Grant editgrant = new Grant("editPerson");
            Grant delgrant = new Grant("deletePerson");
            try {
                Role usrole = SecuritySystem.getRole(context.getUserRole());
                if (usrole.hasGrant(editgrant)) {
                    addChild(e, createImageButton(Image.getImage(Image.EDIT), EditPersonAction.EDIT_PERSON));
                }
                if (usrole.hasGrant(delgrant)) {
                    addChild(e, createImageButton(Image.getImage(Image.DELETE), DeletePersonAction.DELETE_PERSON));
                }
            } catch (DataAccessException ex) {
                //Запилить исключение
            }
        }
        addChild(e, createHiddenTextField(person.getId(), Action.ID));
        return response;
    }

    public static Element getUserRegistrationPage() {
        Element response = createElement(Response.RESPONSE);
        Element e = addChild(response, Response.ENTITY);
        e.setAttribute(Response.EDIT, "true");

        return response;
    }

    public static Element createMoviePersonField(String label, String value, String typekey) {
        return createField(label, value, typekey, Response.MOVIE_PERSON);
    }

    public static Element createTextField(String label, String value, String key) {
        return createField(label, value, key, Response.STRING);
    }

    public static Element createTextField(String label, Number value, String key, String message) {
        String stringValue = null;
        if (value != null) {
            stringValue = value.toString();
        }
        Element e = createField(label, stringValue, key, Response.STRING);
        addChild(e, Response.MESSAGE, message);
        return e;
    }

    public static Element createTextField(String label, String value, String key, String message) {
        Element e = createField(label, value, key, Response.STRING);
        addChild(e, Response.MESSAGE, message);
        return e;
    }

    public static Element createHiddenTextField(String value, String key) {
        return createField(null, value, key, Response.HIDDEN);
    }

    public static Element createHiddenTextField(Number value, String key) {
        return createHiddenTextField(value.toString(), key);
    }

    public static Element createPasswordField(String label, String key) {
        return createField(label, null, key, Response.PASSWORD);
    }

    public static Element createPasswordField(String label, String key, String message) {
        Element e = createField(label, null, key, Response.PASSWORD);
        addChild(e, Response.MESSAGE, message);
        return e;
    }

    public static Element createTextArea(String label, String value, String key) {
        return createField(label, value, key, Response.TEXT);
    }

    public static Element createHeader(String content) {
        return createField(content, null, null, Response.HEADER);
    }

    public static Element createSmallHeader(String content) {
        return createField(content, null, null, Response.SMALL_HEADER);
    }

    public static Element createImage(String value, String key) {
        return createField(null, value, key, Response.IMAGE);
    }

    public static Element createButton(String label, String value, String key) {
        return createField(label, value, key, Response.BUTTON);
    }

    public static Element createButton(String label, String actionName) {
        return createField(label, actionName, Action.ACTION, Response.BUTTON);
    }

    public static Element createLink(String label, String actionName, Number entityId) {
        return createField(label, entityId.toString(), actionName, Response.LINK);
    }

    public static Element createCommentSection(String label, String key, String value) {
        return createField(label, value, key, Response.COMMENT_SECTION);
    }

    public static void createRatingRadios(Element e, String key) {
        for (int i = 0; i < 6; i++) {
            String r = Integer.toString(i);
            addChild(e, createField(r, r, key, Response.RADIO_CONTROL));
        }
    }

    public static Element createLineBreak() {
        Element field = createElement(Response.FIELD);
        addChild(field, Response.TYPE, Response.LINE_BREAK);
        return field;
    }

    public static Element createField(String label, String value, String key, String type) {
        if (label == null && value == null && key == null) {
            return null;
        }

        Element field = createElement(Response.FIELD);

        if (!StringUtil.isEmpty(label)) {
            addChild(field, Response.LABEL, label);
        }
        if (!StringUtil.isEmpty(value)) {
            addChild(field, Response.VALUE, value);
        }
        if (!StringUtil.isEmpty(key)) {
            addChild(field, Response.KEY, key);
        }
        if (!StringUtil.isEmpty(type)) {
            addChild(field, Response.TYPE, type);
        }

        return field;
    }

    public static Element createTextMessage(String message) {
        Element result = createElement(Response.RESPONSE);
        addChild(result, Response.TEXT_MESSAGE, message);
        return result;
    }

    public static Element createSelect(String selectKey, String optionKeys, String optionValues) {
        return createField(selectKey, optionValues, optionKeys, Response.SELECT);
    }

    public static Element createSelect(String label, String selectKey, String optionKeys, String optionValues) {
        Element select = createField(selectKey, optionValues, optionKeys, Response.SELECT);
        addChild(select, Response.MESSAGE, label);
        return select;
    }

    public static Element createImageButton(String label, String value, String key) {
        return createField(label, value, key, Response.IMAGEBUTTON);
    }

    public static Element createImageButton(String label, String actionName) {
        return createField(label, actionName, Action.ACTION, Response.IMAGEBUTTON);
    }

    public static Element createImageLink(String label, String actionName, Number entityId) {
        return createField(label, entityId.toString(), actionName, Response.IMAGELINK);
    }

    /**
     * ************************************************************
     */
    /**
     * Creates an empty XML element.
     *
     * @param root name of element.
     * @return created element.
     */
    public static Element createElement(String root) {
        return new Element(root);
    }

    /**
     * Creates new XML element with text content
     *
     * @param root name of XML element
     * @param content content of XML element.
     * @return created element.
     */
    public static Element createElement(String root, String content) {
        //if(StringUtil.isEmpty(content)) return null;
        Element element = new Element(root);
        element.addContent(content);
        return element;
    }

    /**
     * Creates new XML element with numerical content.
     *
     * @param root name of XML element
     * @param content content of XML element.
     * @return created element.
     */
    public static Element createElement(String root, Number content) {
        //if(content == null) return null;
        return createElement(root, content == null ? null : content.toString());
    }

    /**
     * Puts child element into given parent. Does nothing if
     * <code>child</code> is
     * <code>null</code>.
     *
     * @param parent an element to modify
     * @param child child element.
     * @return
     * <code>parent</code> element.
     */
    public static Element addChild(Element parent, Element child) {
        if (child != null) {
            parent.addContent(child);
        }
        return parent;
    }

    /**
     * Puts child element into given parent.
     *
     * @param parent an element to modify
     * @param childName root of child element
     * @return
     * <code>child</code> element.
     */
    public static Element addChild(Element parent, String childName) {
        Element child = createElement(childName);
        parent.addContent(child);
        return child;
    }

    /**
     * Puts child element into given parent. Does nothing if
     * <code>childValue</code> is
     * <code>null</code>.
     *
     * @param parent an element to modify
     * @param childName root of child element
     * @param childValue value of child element. If
     * <code>null</code> then no element created.
     * @return
     * <code>child</code> element, or
     * <code>null</code> if
     * <code>childValue</code> is null.
     */
    public static Element addChild(Element parent, String childName, String childValue) {
        if (StringUtil.isEmpty(childValue)) {
            return null;
        }
        Element child = createElement(childName);
        child.addContent(childValue);
        parent.addContent(child);
        return child;
    }

    /**
     * Puts child element into given parent. Does nothing if childValue is
     * <code>null</code>.
     *
     * @param parent an element to modify
     * @param childName root of child element
     * @param childValue value of child element. If
     * <code>null</code> then no element created.
     * @return
     * <code>child</code> element, or
     * <code>null</code> if
     * <code>childValue</code> is null.
     */
    public static Element addChild(Element parent, String childName, Number childValue) {
        Element child = createElement(childName);
        //if(childValue == null) return addChild(parent, childName);
        if (childValue == null) {
            return null;
        }
        return addChild(parent, childName, childValue.toString());
    }

    public static void saveXMLToFile(Element root, File f) {
        try {
            BufferedWriter bw = new BufferedWriter(new FileWriter(f));
            XMLOutputter out = new XMLOutputter(Format.getPrettyFormat());
            out.output(root, bw);
            bw.flush();
            bw.close();
        } catch (IOException ex) {
        }
    }

    public static Element toXMLElement(MovieLocal movie, String header,
            Boolean edit, String userlogin, String userRole,
            Map<String, String> messages) throws SystemException {
        Element response = createElement(Response.RESPONSE);
        Element e = addChild(response, Response.ENTITY);
        e.setAttribute(Response.EDIT, edit.toString());

        Date russianReleaseDate = movie.getRussianReleaseDate();
        Date worldReleaseDate = movie.getWorldReleaseDate();
        String countries = movie.getCountries();
        String studio = movie.getStudio();
        Integer budget = movie.getBudget();
        Integer worldCash = movie.getWorldCash();
        Integer length = movie.getLength();
        String title = movie.getTitle();
        String descript = movie.getDescription();
        Double rating = movie.getRating();
        Integer nvotes = movie.getNvotes();
        String genres = movie.getGenres();
        String picture = movie.getPicture();
        Long id = movie.getId();
        HashSet<MoviePersonInfo> persons = movie.getPersons();

        addChild(e, createHeader(header));
        addChild(e, createHiddenTextField(id.toString(), Action.ID));
        addChild(e, createImage(picture, Labels.MOVIE_PICTURE));
        addChild(e, createTextField(Labels.getLabel(Labels.MOVIE_TITLE), title,
                ApplyMovieChangesAction.MOVIE_TITLE,
                messages.get(ApplyMovieChangesAction.MOVIE_TITLE)));
        addChild(e, createTextField(Labels.getLabel(Labels.MOVIE_COUNTRIES), countries, ApplyMovieChangesAction.MOVIE_COUNTRIES));
        if (edit) {
            String g = genres.replace(", ", ";");
            addChild(e, createSmallHeader(Labels.getLabel(Labels.MOVIE_GENRES)));
            addChild(e, createField(ApplyMovieChangesAction.MOVIE_GENRES, g, g, Response.MULTISELECT));
            addChild(e, createField(Labels.getLabel(Labels.MOVIE_PERSON_REMBUTTON), "f_optionDelete(['"
                    + ApplyMovieChangesAction.MOVIE_GENRES + "'])", "", Response.JSBUTTON));
            addChild(e, createLineBreak());
            addChild(e, createLineBreak());
            addChild(e, createHiddenTextField(g, ApplyMovieChangesAction.MOVIE_GENRES));
            try {
                String allg = Provider.getUniqueString(RoleGrantGenreEnum.GENRE);
                addChild(e, createField("allgenres", allg, allg, Response.MULTISELECT));
            } catch (SQLException ex) {
            } catch (NamingException ex) {
            }
            addChild(e, createField(Labels.getLabel(Labels.MOVIE_GENRES_ADDBUTTON), "f_optionMove('allgenres', '"
                    + ApplyMovieChangesAction.MOVIE_GENRES + "')", "", Response.JSBUTTON));
            addChild(e, createLineBreak());
        } else {
            addChild(e, createTextField(Labels.getLabel(Labels.MOVIE_GENRES), genres, ApplyMovieChangesAction.MOVIE_GENRES));
        }
        try {

            String worldReleaseDateLabel = Labels.getLabel(Labels.MOVIE_WLDRELEASEDATE);
            if (edit) {
                worldReleaseDateLabel += Labels.getLabel(Labels.DATE_FORMAT);
            }
            addChild(e, createTextField(worldReleaseDateLabel,
                    TypeConverter.convertToString(worldReleaseDate),
                    ApplyMovieChangesAction.MOVIE_WLDRELEASEDATE,
                    messages.get(ApplyMovieChangesAction.MOVIE_WLDRELEASEDATE)));

            String russianReleaseDateLabel = Labels.getLabel(Labels.MOVIE_RUSRELEASEDATE);
            if (edit) {
                russianReleaseDateLabel += Labels.getLabel(Labels.DATE_FORMAT);
            }
            addChild(e, createTextField(russianReleaseDateLabel,
                    TypeConverter.convertToString(russianReleaseDate),
                    ApplyMovieChangesAction.MOVIE_RUSRELEASEDATE,
                    messages.get(ApplyMovieChangesAction.MOVIE_RUSRELEASEDATE)));
        } catch (ConversionException ex) {
        }
        if (edit) {
            addChild(e, createSmallHeader(Labels.getLabel(Labels.MOVIE_PERSON_ACTOR)
                    + ", " + Labels.getLabel(Labels.MOVIE_PERSON_DIRECTOR) + ", "
                    + Labels.getLabel(Labels.MOVIE_PERSON_PRODUCER) + ": "));
            String[] person_types = {MoviePersonInfo.ACTOR, MoviePersonInfo.DIRECTOR, MoviePersonInfo.PRODUCER};
            String s = "";
            StringBuilder sb_keys;
            StringBuilder sb_conts;
            for (String mptype : person_types) {
                sb_keys = new StringBuilder();
                sb_conts = new StringBuilder();
                for (MoviePersonInfo mp : persons) {
                    if (mptype.equals(mp.type)) {
                        sb_keys.append(mp.id);
                        sb_keys.append(";");
                        sb_conts.append(mp.name);
                        sb_conts.append(";");
                    }
                }
                if (mptype.equals(MoviePersonInfo.ACTOR)) {
                    s = ApplyMovieChangesAction.MOVIE_PERSONS_ACTORS;
                } else if (mptype.equals(MoviePersonInfo.DIRECTOR)) {
                    s = ApplyMovieChangesAction.MOVIE_PERSONS_DIRECTORS;
                } else if (mptype.equals(MoviePersonInfo.PRODUCER)) {
                    s = ApplyMovieChangesAction.MOVIE_PERSONS_PRODUCERS;
                }
                addChild(e, createField(s, sb_conts.toString(), sb_keys.toString(), Response.MULTISELECT));
                addChild(e, createHiddenTextField(sb_keys.toString(), s));
            }

            PersonLocalHome pHome = null;
            try {
                pHome = EntityUtil.getPersonHome();
            } catch (NamingException ex) {
                throw new SystemException(Labels.getLabel(Labels.CANNOT_FIND_LOCAL_HOME_OBJECT_MESSAGE), ex);
            }
            HashMap allpersons = pHome.getAll();
            sb_keys = new StringBuilder();
            sb_conts = new StringBuilder();
            Iterator i = allpersons.keySet().iterator();
            Long k;
            while (i.hasNext()) {
                k = (Long) i.next();
                sb_keys.append(k.toString());
                sb_keys.append(";");
                sb_conts.append(allpersons.get(k));
                sb_conts.append(";");
            }
            addChild(e, createField(Labels.getLabel(Labels.MOVIE_PERSON_REMBUTTON), "f_optionDelete(['"
                    + ApplyMovieChangesAction.MOVIE_PERSONS_ACTORS + "','"
                    + ApplyMovieChangesAction.MOVIE_PERSONS_DIRECTORS + "','"
                    + ApplyMovieChangesAction.MOVIE_PERSONS_PRODUCERS + "'])", "noname", Response.JSBUTTON));
            addChild(e, createLineBreak());
            addChild(e, createField(Labels.getLabel(Labels.MOVIE_PERSON_ADDBUTTON), "f_optionMove('allpersons', this.form.personType.options[personType.selectedIndex].value)", "name", Response.JSBUTTON));
            addChild(e, createField("personType", Labels.getLabel(Labels.MOVIE_PERSON_ACTOR) + ";"
                    + Labels.getLabel(Labels.MOVIE_PERSON_DIRECTOR) + ";"
                    + Labels.getLabel(Labels.MOVIE_PERSON_PRODUCER),
                    "actors;directors;producers", Response.SELECT));
            addChild(e, createField("allpersons", sb_conts.toString(), sb_keys.toString(), Response.MULTISELECT));
            addChild(e, createField("Search person", "MyUtil.selectFilter('allpersons', this.value)", "filter", Response.JSTINPUT));
        } else {
            addChild(e, createSmallHeader(Labels.getLabel(Labels.MOVIE_PERSON_ACTOR)));
            for (MoviePersonInfo info : persons) {
                if (info.getType().equals(MoviePersonInfo.ACTOR)) {
                    addChild(e, createLink(info.getName(), ViewPersonAction.VIEW_PERSON, info.getId()));
                }
            }
            addChild(e, createSmallHeader(Labels.getLabel(Labels.MOVIE_PERSON_DIRECTOR)));
            for (MoviePersonInfo info : persons) {
                if (info.getType().equals(MoviePersonInfo.DIRECTOR)) {
                    addChild(e, createLink(info.getName(), ViewPersonAction.VIEW_PERSON, info.getId()));
                }
            }
            addChild(e, createSmallHeader(Labels.getLabel(Labels.MOVIE_PERSON_PRODUCER)));
            for (MoviePersonInfo info : persons) {
                if (info.getType().equals(MoviePersonInfo.PRODUCER)) {
                    addChild(e, createLink(info.getName(), ViewPersonAction.VIEW_PERSON, info.getId()));
                }
            }


        }
        addChild(e, createTextField(Labels.getLabel(Labels.MOVIE_STUDIO),
                studio, ApplyMovieChangesAction.MOVIE_STUDIO));
        addChild(e, createTextField(Labels.getLabel(Labels.MOVIE_LENGTH),
                length, ApplyMovieChangesAction.MOVIE_LENGTH,
                messages.get(ApplyMovieChangesAction.MOVIE_LENGTH)));
        if (edit) {
//            addChild(e, createTextField(Labels.getLabel(Labels.MOVIE_ADD_RATE), rating.toString(), ApplyMovieChangesAction.MOVIE_RATING));                
        } else {
            DecimalFormat df = new DecimalFormat("0.##");
            addChild(e, createTextField(Labels.getLabel(Labels.MOVIE_RATING), df.format(rating), ApplyMovieChangesAction.MOVIE_RATING));
            addChild(e, createTextField(Labels.getLabel(Labels.MOVIE_VOTED), nvotes.toString(), Labels.MOVIE_VOTED));
        }
        DecimalFormat df = new DecimalFormat("###,###,###,##0");
        addChild(e, createTextArea(Labels.getLabel(Labels.MOVIE_DESCRIPTION), descript, ApplyMovieChangesAction.MOVIE_DESCRIPTION));
        addChild(e, createTextField(Labels.getLabel(Labels.MOVIE_BUDGET),
                df.format(budget), ApplyMovieChangesAction.MOVIE_BUDGET,
                messages.get(ApplyMovieChangesAction.MOVIE_BUDGET)));
        addChild(e, createTextField(Labels.getLabel(Labels.MOVIE_CASH),
                df.format(worldCash), ApplyMovieChangesAction.MOVIE_CASH,
                messages.get(ApplyMovieChangesAction.MOVIE_CASH)));

        Role role = RoleManager.getRoleManager().getRole(userRole);
        if (edit) {
            if (id.equals(Long.valueOf(0))) {
                if (role.hasGrant(Grants.CREATE_MOVIE)) {
                    addChild(e, createField(Image.getImage(Image.CREATE_MOVIE), CreateMovieAction.CREATE_MOVIE, Action.ACTION, Response.IMAGEBUTTON));
                }
            } else {
                if (role.hasGrant(Grants.EDIT_MOVIE)) {
                    addChild(e, createField(Image.getImage(Image.APPLY), ApplyMovieChangesAction.APPLY_MOVIE_CHANGES, Action.ACTION, Response.IMAGEBUTTON));
                }
            }
        } else {
            if (role.hasGrant(Grants.EDIT_MOVIE)) {
                addChild(e, createImageButton(Image.getImage(Image.EDIT), EditMovieAction.EDIT_MOVIE));
                //addChild(e, createField(Labels.getLabel(Labels.EDIT_MOVIE), EditMovieAction.EDIT_MOVIE, Action.ACTION, Response.BUTTON));
            }
            if (role.hasGrant(Grants.DELETE_MOVIE)) {
                addChild(e, createImageButton(Image.getImage(Image.DELETE), DeleteMovieAction.DELETE_MOVIE));
                //addChild(e, createField(Labels.getLabel(Labels.DELETE_MOVIE_BUTTON), DeleteMovieAction.DELETE_MOVIE, Action.ACTION, Response.BUTTON));
            }
            if (!StringUtil.isEmpty(userlogin)) {
                LinkedList<Comment> comments = movie.getComments();
                addChild(e, createLineBreak());
                addChild(e, createLineBreak());
                addChild(e, createImageButton(Image.getImage(Image.RATE_MOVIE), AddRateAction.MOVIE_RATE_ADD));
                //addChild(e, createField(Image.getImage(Image.RATE_MOVIE), AddRateAction.MOVIE_RATE_ADD, Action.ACTION, Response.IMAGEBUTTON));
                createRatingRadios(e, AddRateAction.MOVIE_RATE_VALUE);
                addChild(e, createCommentSection(Labels.getLabel(Labels.MOVIE_COMMENT_NEW), CreateCommentAction.CONTENT, "Place your comment here"));
                addChild(e, createField(Image.getImage(Image.LEAVE_COMMENT), CreateCommentAction.CREATE_COMMENT, Action.ACTION, Response.IMAGEBUTTON));
                addChild(e, createLineBreak());
                addChild(e, createLineBreak());
                addChild(e, createSmallHeader(Labels.getLabel(Labels.MOVIE_COMMENTS)));
                addChild(e, createSmallHeader("<hr>"));
                for (Comment com : comments) {
                    addChild(e, createLink(com.getUsername(), ViewProfileAction.VIEW_PROFILE, com.getUserId()));
                    try {
                        addChild(e, createTextArea(Labels.getLabel(Labels.MOVIE_COMMENT_DATE), TypeConverter.convertToStringWithTime(com.getEditDate()), "editDate"));
                        if (com.getUsername().equals(userlogin)) {
                            addChild(e, createImageLink(Image.getImage(Image.DELETE), DeleteCommentAction.DELETE_COMMENT, com.getId()));
                        }
                        addChild(e, createTextArea(Labels.getLabel(Labels.MOVIE_COMMENT_CONTENT), com.getContent(), "content"));
                    } catch (ConversionException ex) {
                        //                    throw new ActionExecutionException("Date conversion exception", ex);
                    }
                    addChild(e, createSmallHeader("<hr>"));
                }
            }
        }
        return response;
    }

    public static Element createLink(String label, String actionName, String entityId) {
        return createField(label, entityId, actionName, Response.LINK);
    }
}
